package com.game.websockt;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.game.websockt.MessageJson.MsgType;



@ServerEndpoint(value = "/chat/{user_name}/{user_pass}")
public class Websockets   {
	
	    private static final String GUEST_PREFIX = "Guest";
	    private static final AtomicInteger connectionIds = new AtomicInteger(0);
	    private static final Set<Websockets> connections = new CopyOnWriteArraySet<Websockets>();
	    
	    private static final Map<Object, String> mapnemas=new HashMap<>();
	    
	    private static final List<Map<String, Object>> list=new ArrayList<>();
	    
	    private static final List<Map<String, Object>> alllist=new ArrayList<>();
	 
	    private String nickname;
	    private Session session;
	
	Logger log = null;
	public Websockets() {
		log = Logger.getGlobal();
    	
	}
	
	@OnOpen
	public void  start(@PathParam("user_name") String name, @PathParam("user_pass")String pass,Session session) {
		this.session=session;
		connections.add(this);
	
		//验证用户
		if(null!=name&&null!=pass) {
			mapnemas.put(session,name);
			
			nickname = name;
			//用户名验证合法
			log.info("合法用户名："+name+"密码："+pass);
			//发送提示登陆成功
			Map<String, Object> map=new HashMap<>();
			MessageJson msg=new MessageJson();
				msg.setType(MsgType.LOGIN);
				msg.setMsg("登陆成功");
				msg.setCode("SUCCESS");
				msg.setFrom(name);
				msg.setTo(name);
				map.put("msg", msg);
			User user=new User();
				user.setName(name);
				user.setId(session.getId());
				map.put("user", user);
			send2user(JSON.toJSONString(map), session);
			
			//发送更新用户登陆列表
			Map<String, Object> mapOnline=new HashMap<>();
			MessageJson msgOnline=new MessageJson();
				msgOnline.setType(MsgType.ONLINE);
				msgOnline.setMsg(name+"上线了");
				
				mapOnline.put("msg", msgOnline);
				
				 User ms=null;
				 List<Object> onlinelist=new ArrayList<>();
				for (Websockets websockets : connections) {
					  ms=new User();
					  ms.setName(websockets.nickname);
					  ms.setId(websockets.session.getId());
					  onlinelist.add(ms);
				 }
			     mapOnline.put("onlinelist", JSON.toJSONString(onlinelist));
			
			//send2other(JSON.toJSONString(mapOnline),  session);
			broadcast(JSON.toJSONString(mapOnline));
		}else {
			nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
			log.info("非法用户名："+nickname+"密码："+pass);
			mapnemas.put(session,nickname);
		}
		
		
	}

		 
		 

	@SuppressWarnings("unchecked")
	@OnMessage
     public void incoming(@PathParam("user_name") String name, @PathParam("user_pass")String pass,String message) {
		  log.info(name+"------------------"+message+session.getOpenSessions());  
	      try {  
//	    	 Map<String, Object>  map=new HashMap<String, Object>();
//	 		 map.put("type", "msg");
//	 		 MessageJson obj = JSON.parseObject(message.toString(), MessageJson.class);
//	 		 map.put("mstobj", obj);
	    	  MessageJson msg = JSON.parseObject(message, MessageJson.class);
	    	  String msgstr = msg.getMsg();
	    	  String num = msg.getTo();
	    	 
	    	  if(msgstr.equals("GET_USER_GROUP")) {
	    			//发送提示登陆成功
	  			Map<String, Object> map=new HashMap<>();
	  				msg.setType(MsgType.GET_USER_GROUP);
	  				msg.setMsg("获取玩家数据");
	  				msg.setCode("SUCCESS");
	  				map.put("msg", msg);
	  			
	  				
	  				send2user(JSON.toJSONString(map), session);
	    	  }
	 		 send2other(message, session);
	      } catch (Exception e) {  
	        e.printStackTrace();  
	      }  
	        
	  } 

	@OnClose
     public void end() {
		// TODO Auto-generated method stub
		//log.log(Level.INFO, "�ر�closeReason");
		connections.remove(this);
		mapnemas.remove(session);
		
	}
	
	@OnError
	 public void onError(Throwable t) throws Throwable {
		// TODO Auto-generated method stub
		//log.log(Level.INFO, "��������onError");
	}
	
	private void send2user(String msg,Session session){
			 try {
				session.getBasicRemote().sendText(msg);
			} catch (IOException e) {
				e.printStackTrace();
			}
		
	}
	 private  void broadcast(String msg) {
	        for (Websockets wb : connections) {
	            	try {
	            		log.info(wb.session.getBasicRemote()+"+++");
	            		 wb.session.getBasicRemote().sendText(msg);
					} catch (Exception e) {
						e.printStackTrace();
						  connections.remove(wb);
						  mapnemas.remove(wb.session);
						try {
						  wb.session.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
	            	
	        }
	    }
	 private void send2other(String string, Session session2) {
			// TODO Auto-generated method stub
			 for (Websockets wb : connections) {
	         	try {
	         		if (wb.session!=session2) {
	         			wb.session.getBasicRemote().sendText(string);
					 }
	         		 
					} catch (Exception e) {
						e.printStackTrace();
						  connections.remove(wb);
						try {
						  wb.session.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
	         	
	     }
		}
	 
	 private void sendAll(String string, Session session2) {
			// TODO Auto-generated method stub
			 for (Websockets wb : connections) {
	         	try {
	         			//wb.session.getBasicRemote().sendText(string);
	         			wb.session.getAsyncRemote().sendText(string);
	         		 
					 }catch (Exception e) {
						e.printStackTrace();
						  connections.remove(wb);
						try {
						  wb.session.close();
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
	         	
	     }
		}
	 
	
}
